<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Question Class
 *
 * @category  Home
 */
class QuestionAction extends HomeAction
{

    protected $Question;


    function _initialize()
	{
		parent::_initialize();
		$this->Question = D('Question');
	}


	//自动处理问题状态
    public function _before_details()
	{
		$qstID = intval($_GET['qid']);
		$question = $this->Question->find($qstID);

		if (1 == $question['is_locked'] || in_array($question['status'], array(0,3)))
		{
			return;
		}

		import('ORG.Net.Http');

		$time = time();
		$isExpired = $question['expire_time'] < $time;
		if ($isExpired)
		{
			$asker = $this->_User->find($question['poster_id']);
			if(1 == $question['status'])
			{
				//有答案自动进入投票
				if ($question['answer_count'] > 0)
				{
					$expiration = $this->_global['vote_expiration'];
					$map = array('question_id' => $qstID);
					$data = array(
						'status' => 2,
						'expire_time' => $time + 86400 * $expiration,
					);
					$this->Question->where($map)->save($data);
				}
				else
				{
					//关闭过期问题以及发送通知
					if ($this->_global['close_expired_question_enable'])
					{
						if ($asker['new_answer_alert'])
						{
							$requestUrl = get_site_domain(). U('Notification/closeExpiredQuestionAlert', array('qid' => $qstID));
							Http::async_request($requestUrl);
						}
						$map = array('question_id' => $qstID);
						$data = array('status' => 0);
						$this->Question->where($map)->save($data);	
					}
					else 
					{
						$map = array('question_id' => $qstID);
						$data = array('expire_time' => $time + 12 * 3600);
						$this->Question->where($map)->save($data);
					}
					
				}
			}
			elseif (2 == $question['status'])
			{
				$Answer = M('Answer');
				$votes = array();
				$map = array('question_id' => $qstID);

				$answers = $Answer->where($map)->select();
				if (!empty($answers))
				{
					foreach ($answers as $value)
					{
						$votes[$value['answer_id']] = $value['vote_count'];
					}
				}

				$votes['no_best_answer'] = $question['no_best_vote_count'];
				$max = max($votes);
				$repeat = array_count_values($votes);

				//非平局的投票
				if (count($votes) > 1 && 1 == $repeat[$max])
				{
					$ansID = array_search($max, $votes);
					if ('no_best_answer' == $ansID)
					{
						//归还提问者积分
						$points = get_activity_points('no_best_answer');
						$this->_User->updatePointCount($question['user_id'], $points);

						//发送关闭未解决问题通知(通知提问者)
						if ($asker['new_answer_alert'])
						{
							$requestUrl = get_site_domain(). U('Notification/closeUnresolvedQuestionAlert', array('qid' => $qstID));
							Http::async_request($requestUrl);
						}
						$map  = array('question_id' => $qstID);
						$data = array('status' => 0);
						$this->Question->where($map)->save($data);
					}
					else
					{
						$map  = array('answer_id' => $ansID);
						$data = array('is_best' => 1);
						$Answer->where($map)->save($data);

						$map  = array('question_id' => $qstID);
						$data = array(
							'resolve_time'=> $time,
							'status' => 3,
						);
						$this->Question->where($map)->save($data);

						$temp = list_search($answers, array('answer_id' => $ansID));
						$answer = $temp[0];
						$answerer = $this->_User->find($answer['poster_id']);

						//奖励最佳回答者
						$points = get_activity_points('best_answer');
						$this->_User->updatePointCount($answerer['user_id'], $points);
						$this->_User->logActivity($answerer['user_id'], 'best_answer', $points, $qstID);

						//发送最佳答案通知(通知回答者)
						if ($answerer['best_answer_alert'])
						{
							$requestUrl = get_site_domain(). U('Notification/selectedAsBestAnswerAlert', array('aid' => $ansID));
							Http::async_request($requestUrl);
						}

						//发送票选最佳答案通知(通知提问者)
						if ($asker['new_answer_alert'])
						{
							$requestUrl = get_site_domain(). U('Notification/votedAsBestAnswerAlert', array('qid' => $qstID));
							Http::async_request($requestUrl);
						}
					}
				}
				else
				{
					//投票结束期延长12小时
					$map  = array('question_id' => $qstID);
					$data = array('expire_time' => $time + 12 * 3600);
					$this->Question->where($map)->save($data);
				}
			}
		}
	}


	//问题详情
	public function details()
    {

        $qstID = intval($_GET['qid']);
    	$sort = isset($_GET['sort']) ? intval($_GET['sort']) : -1;
        $question = $this->Question->find($qstID);
    	if (empty($question))
    	{
    		$this->error(L('question_not_existed'));
    	}

    	//更新浏览计数
    	$this->Question->updateViewCount($qstID);

    	$htmlExpiration = intval($this->_global['cache_question_page_expiration'] * 60);
    	$htmlFile = HTML_PATH . date('Y', $question['create_time']) .'/'. date('m', $question['create_time']) .'/'. $qstID .'.html';

    	/*--------------------- 给游客加载静态问题页面 -----------------------*/
    	if ($htmlExpiration > 0 && 6 == $this->_user['user_group'] && -1 == $sort)
    	{
    	    if (file_exists($htmlFile) && filemtime($htmlFile) + $htmlExpiration > time())
    		{
    			readfile($htmlFile);
    			exit;
    		}
    	}

    	$isModerator = is_moderator($this->_user['user_id'], $this->_user['admin_group'], $question['category_id']);
    	if (($question['poster_id'] != $this->_user['user_id']) && (0 == $question['is_visible'] && !$isModerator))
    	{
    		$this->error(L('no_read_question_perms'));
    	}

    	$question['asker'] = $this->_User->find($question['poster_id']);
    	$question['tags']  = $this->_global['tag_enable'] ? $this->Question->getQuestionTags($qstID) : array();
    	$question['breadcrumbs'] = get_category_path($question['category_id']);
    	$question['urgent_points'] = get_activity_points('urgent');
    	

		/*--------------- 用户权限说明 -----------------
		 * 1.管理组可以全天候行使权限
         * 2.用户组行使权限受问题状态的限制（问题和答案只有在开放状态下可编辑和删除，评论随时可删除）
		 */
		$perms = array(
			'allow_answer'             => 0,
			'allow_choose_answer'      => 0,
			'admin_delete_question'    => 0,
			'admin_delete_answer'      => 0,
			'allow_delete_question'    => 0,
			'allow_delete_answer'      => 0,
			'allow_edit_question'      => 0,
			'allow_edit_answer'        => 0,
			'allow_extend_expiration'  => 0,
			'admin_edit_question'      => 0,
			'admin_edit_answer'        => 0,
			'allow_email_question'     => 0,
			'allow_follow_question'    => 0,
			'allow_improve_answer'     => 0,
			'allow_put_to_vote'        => 0,
			'allow_rate'               => 0,
			'allow_report'             => 0,
			'allow_star_question'      => 0,
			'allow_view_ip'            => 0,
			'allow_vote'               => 0,
		);

		$perms['allow_rate'] = $this->_userGroup['allow_rate'];
		$perms['allow_report'] = $this->_userGroup['allow_report'];
    	$perms['allow_view_ip'] = ($this->_user['user_id'] == $question['poster_id']) || ($isModerator && check_moderator_perms($this->_user['admin_group'],'allow_view_ip'));
    	$perms['allow_star_question'] = $this->_userGroup['allow_star_question'] && !empty($this->_user['user_id']) && ($this->_user['user_id'] != $question['poster_id']);
    	$perms['allow_email_question'] = $this->_userGroup['allow_email_question'] && !empty($this->_user['user_id']);
        $perms['allow_follow_question'] = $this->_userGroup['allow_follow_question'] && !empty($this->_user['user_id']) && ($this->_user['user_id'] != $question['poster_id']);

        $myAnswerCount = $myVoteCount = 0;
        
        switch ($question['status'])
    	{
    		case 1:
    			$perms['allow_answer'] = $this->_userGroup['allow_answer'];
    			$perms['allow_edit_answer'] = $this->_userGroup['allow_edit_answer'];
    			$perms['allow_choose_answer'] = ($this->_user['user_id'] == $question['poster_id']) && (time() - $question['create_time'] > 3600);
    			$perms['allow_delete_answer'] = $this->_userGroup['allow_delete_answer'];
    			
    			$perms['allow_add_details'] = ($this->_user['user_id'] == $question['poster_id']);
    			$perms['allow_put_to_vote'] = ($this->_user['user_id'] == $question['poster_id']) && (time() - $question['create_time'] > 3600) && ($question['answer_count'] > 1);
    			$perms['allow_extend_expiration'] = ($this->_user['user_id'] == $question['poster_id']) && ($question['expire_time'] < $question['create_time'] + ($this->_global['question_expiration'] + 4) * 86400);
    			
    			$perms['allow_edit_question'] = ($this->_user['user_id'] == $question['poster_id']) && $this->_userGroup['allow_edit_question'];
    			$perms['allow_delete_question'] = ($this->_user['user_id'] == $question['poster_id']) && $this->_userGroup['allow_delete_question'];
    			break;
    		
    		case 2:
    			$map = array(
    				'type'       => 'vote',
    				'user_id'    => $this->_user['user_id'],
					'related_id' => $qstID,
				);
				$Activity = M('Activity');
				$myVoteCount = $Activity->where($map)->count();
				$perms['allow_vote'] = $this->_userGroup['allow_vote'] && $myVoteCount < 1;
				break;
				
    		case 3:
    			$perms['allow_improve_answer'] = $this->_userGroup['allow_answer'] && $this->_userGroup['allow_answer_resolved_question'];
				$perms['allow_edit_answer'] = $this->_userGroup['allow_edit_answer'];
				$perms['allow_delete_answer'] = $this->_userGroup['allow_delete_answer'];
    			
				$Feedback = M('QuestionFeedback');
    		    $question['feedback'] = $Feedback->find($qstID);
    			break;
    	}
    	
    	if (in_array($question['status'], array(1,3)))
    	{
    		$map = array(
				'question_id' => $qstID,
				'poster_id'   => $this->_user['user_id'],
			);
			$Answer = M('Answer');
			$myAnswerCount = $Answer->where($map)->count();	
    	}
		
    	if (!$this->_userGroup['allow_answer_own_question'])
		{
			$perms['allow_answer'] = $perms['allow_answer'] && ($this->_user['user_id'] != $question['poster_id']);
			$perms['allow_improve_answer'] = $perms['allow_improve_answer'] && ($this->_user['user_id'] != $question['poster_id']);
		}
		
		if (!$this->_userGroup['allow_multiple_answer'])
		{
			$perms['allow_answer'] = $perms['allow_answer'] && $myAnswerCount < 1;
			$perms['allow_improve_answer'] = $perms['allow_improve_answer'] && $myAnswerCount < 1;
		}

    	$perms['admin_edit_question'] = $isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_edit_question');
    	$perms['admin_delete_question'] = $isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_delete_question');
        $perms['admin_edit_answer'] = $isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_edit_answer');
    	$perms['admin_delete_answer'] = $isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_delete_answer');

    	/*------------------- 问题答案 ---------------------*/
    	$parameter = '';
    	$answers = $map  = $order = array();
    	$order['is_best'] = 'desc';
    	switch ($sort)
    	{
    		case 1:
    			$order['answer_id'] = 'asc';
    		break;
    		case -1:
    			$order['answer_id'] = 'desc';
    		break;
    		case 2:
    			$order['down_rate_count'] = 'desc';
    		break;
    		case -2:
    			$order['up_rate_count'] = 'desc';
    		break;
    	}
    	$parameter .= '&sort='.$sort;

    	$map['question_id'] = $qstID;
    	$map['is_visible'] = 1;

    	import('ORG.Util.Page');
    	
    	$AnswerView = D('AnswerView');

    	$pageSize = $this->_global['answers_per_page'];
    	$Page = new Page($question['answer_count'], $pageSize);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
    	$answers = $AnswerView->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();
    	
    	if (!empty($answers))
    	{
    		$TeamUser = D('TeamUser');
    		foreach ($answers as $key => $answer)
    		{
    			if ($answer['is_teamwork'])
    			{
    				$isTeamUser = $TeamUser->isTeamUser($this->_user['user_id'], $answer['team_id']);
    				$allowEditAnswer = $perms['allow_edit_answer'] && $isTeamUser;
    				$allowReport = 0;
    			}
    			else 
    			{
    				$allowEditAnswer = $perms['allow_edit_answer'] && $this->_user['user_id'] == $answer['poster_id'];	
    			}
    			
    			$answers[$key]['allow_edit_answer'] = $allowEditAnswer;
    			$answers[$key]['is_hidden'] = ($answer['down_rate_count'] - $answer['up_rate_count'] >= 5) && (3 == $question['status']) ? 1 : 0;
    			$answers[$key]['allow_report_answer'] = $allowReport && $this->_user['user_id'] != $answer['poster_id'];
    			$answers[$key]['allow_vote_answer'] = $perms['allow_vote'] && $this->_user['user_id'] != $answer['poster_id'];
    			$answers[$key]['allow_rate_answer'] = $perms['allow_rate'] && $this->_user['user_id'] != $answer['poster_id'];
    			$answers[$key]['allow_delete_answer'] = $perms['allow_delete_answer'] && $this->_user['user_id'] == $answer['poster_id'];
    		}
    	}

    	$seo = array(
    		'title' => $question['title'],
    		'keywords' => $question['title'],
    		'description' => kg_substr($question['details'], 0, 150),
    	);
    	
    	$loginUrl = U('Account/login');
    	$registerUrl = U('Account/register');
    	L('answer_require_login', sprintf(L('answer_require_login'), $loginUrl, $registerUrl));

    	$this->assign('seo', $seo);
    	$this->assign('sort', $sort);
    	$this->assign('perms', $perms);
    	$this->assign('question', $question);
    	$this->assign('myAnswerCount', $myAnswerCount);
    	$this->assign('answers', $answers);
    	$this->assign('pagination', $pagination);

    	/*---------------------- 给游客生成静态问题页面 ------------------------*/
    	if ($htmlExpiration > 0 && 6 == $this->_user['user_group'] && -1 == $sort)
    	{
    	    if (!is_dir(dirname($htmlFile)))
    	    {
    	    	@mkdir(dirname($htmlFile), 0777, true);
    	    }
    	    if (!file_exists($htmlFile) || filemtime($htmlFile) + $htmlExpiration < time())
    		{
    			$html = $this->fetch();
    			@file_put_contents($htmlFile, $html);
    		}
    	}
    	$this->display();
    }


    //补充问题
    public function addDetails()
    {

        $qstID = intval($_REQUEST['qid']);
        $question = $this->Question->find($qstID);
        if (empty($question))
        {
        	$this->error(L('question_not_existed'));
        }
        
        $captcha = require_captcha_when('post', $this->_user['user_group']);

        $allow = ($this->_user['user_id'] == $question['poster_id']) && (1 == $question['status']);
        if (!$allow)
        {
            $this->error(L('no_perms_action'));
        }

        if ($this->isPost())
        {
    		$minPostChars = $this->_global['min_post_chars'];
    		$maxPostChars = $this->_global['max_post_chars'];
    		if (strlen($_POST['details']) < $minPostChars)
    		{
    			$this->error(L('too_few_characters'));
    		}
    		if (strlen($_POST['details']) > $maxPostChars)
    		{
    			$this->error(L('too_much_characters'));
    		}

    		if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
    		{
    			$this->error(L('captcha_incorrect'));
    		}

    		$details = addslashes($question['details']) ."\n". trim($_POST['details']);
    		$data  = array('details' => $details);
    		$where = array('question_id' => $qstID);
    		$this->Question->where($where)->save($data);
    		$this->success(L('question_details_added'));
        }
        else
        {
            $this->assign('captcha', $captcha);
            $this->assign('question', $question);
            $html = $this->fetch();
            exit($html);
        }
    }


    //延长过期时间
    public function extendExpiration()
    {

        $qstID = intval($_REQUEST['qid']);
        $question = $this->Question->find($qstID);
        if (empty($question))
        {
        	$this->error(L('question_not_existed'));
        }

        //权限检查
        $allow = $this->_user['user_id'] == $question['poster_id'] && 1 == $question['status'];
        if (!$allow)
        {
        	$this->error(L('no_perms_action'));
        }

        $max = 4; //最长时限
        $step = 2; //步进值
        if (($question['expire_time'] - $question['create_time']) < 86400 * ($this->_global['question_expiration'] + $max))
        {
            $extend = $step * 86400;
            $data = array('expire_time' => array('exp', 'expire_time+'.$extend));
            $where = array('question_id' => $qstID);
            $this->Question->where($where)->save($data);
        }

        $url = format_question_url($question['question_id'], $question['title']);
        redirect($url);
    }


    //转问题状态为投票
    public function putToVote()
    {

        $qstID = intval($_REQUEST['qid']);
        $question = $this->Question->find($qstID);
        if (empty($question))
        {
        	$this->error(L('question_not_existed'));
        }

        //权限检查
        $allow = ($this->_user['user_id'] == $question['poster_id']) && (1 == $question['status']) && (time() - $question['create_time']>3600) && ($question['answer_count'] > 1);
        if (!$allow)
        {
        	$this->error(L('no_perms_action'));
        }

        $data = array('status' => 2);
        $where = array('question_id' => $qstID);
        $this->Question->where($where)->save($data);

        $url = format_question_url($question['question_id'], $question['title']);
        redirect($url);
    }


    //(启用/关闭)新答案通知
    public function switchAnswerAlert()
    {

        $qstID = intval($_GET['qid']);
        $status = in_array($_GET['status'], array(0,1)) ? intval($_GET['status']) : 1;

        $question = $this->Question->find($qstID);
        if (empty($question))
        {
        	$this->error(L('question_not_existed'));
        }
        if ($question['poster_id'] != $this->_user['user_id'])
        {
        	$this->error(L('no_perms_action'));
        }

        $where = array('question_id' => $qstID);
        $data  = array('new_answer_alert' => $status);
    	$this->Question->where($where)->save($data);

    	$url = format_question_url($question['question_id'], $question['title']);
        redirect($url);
    }


    //下一个问题
    public function showAnother()
    {

        $qstID = intval($_GET['qid']);
        $question = $this->Question->find($qstID);
        if (empty($question))
        {
        	$this->error(L('question_not_existed'));
        }

        $map = array();
        $cateID = $question['category_id'];
        if ($cateID)
        {
            $cateIDs = get_sub_category_ids($cateID, 1);
            $map['category_id'] = array('in', $cateIDs);
        }
        $map['status'] = $question['status'];
        $map['is_visible'] = 1;
        $map['question_id'] = array('gt', $qstID);
        $result = $this->Question->where($map)->find();

        if (empty($result))
        {
            $map['question_id'] = array('lt', $qstID);
            $result = $this->Question->where($map)->find();
        }
        $url = empty($result) ? format_category_url($cateID) : format_question_url($result['question_id'], $result['title']);
        redirect($url);
    }


    //电邮分享问题
    public function share()
    {

    	$qstID  = intval($_REQUEST['qid']);
    	$question = $this->Question->find($qstID);

    	$captcha = require_captcha_when('email', $this->_user['user_group']);

    	if ($this->isPost())
    	{
        	if (empty($question))
        	{
        	 	$this->error(L('question_not_existed'));
        	}

        	if (exceed_activity_limit($this->_user['user_id'], $this->_user['user_group'], 'email'))
        	{
        		$this->error('exceed_email_limit');
        	}

			$addresses = explode(',', $_POST['recipient']);
			foreach ($addresses as $value)
			{
				if(!is_valid_email(trim($value)))
				{
					$this->error(L('email_invalid'));
				}
			}

			if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
			{
				$this->error(L('captcha_incorrect'));
			}

			if (!empty($_POST['cc']))
			{
				array_push($addresses, $this->_user['email']);
			}

			$recipient = implode(',', $addresses);
			$message = $_POST['message'];

			$Mailer = A('Mailer');
			$result = $Mailer->shareQuestion($this->_user['user_id'], $qstID, $recipient, $message);
			if ($result)
			{
			    $this->_User->logActivity($this->_user['user_id'], 'email', 0, 0);
			    $this->success(L('send_email_ok'));
			}
			else
			{
				$this->error(L('send_email_failed'));
			}
    	}
    	else
    	{
    	    $this->assign('captcha', $captcha);
    		$this->assign('question', $question);
    		$html = $this->fetch();
    		exit($html);
    	}
    }


    //提出问题
    public function ask()
    {

    	$captcha = require_captcha_when('post', $this->_user['user_group']);
    	
    	//用户权限检查
    	if (!$this->_userGroup['allow_ask'])
    	{
    		$this->error(L('no_perms_action'));
    	}

    	if (isset($_POST['op']) && $this->isPost())
    	{
			//activity限制检查
        	if (exceed_activity_limit($this->_user['user_id'], $this->_user['user_group'], 'ask'))
        	{
        		$this->error(L('exceed_ask_limit'));
        	}

			//内容长度检查
    		$minTitleChars = $this->_global['min_title_chars'];
    		$maxTitleChars = $this->_global['max_title_chars'];
    		$minPostChars  = $this->_global['min_post_chars'];
    		$maxPostChars  = $this->_global['max_post_chars'];
    		if (strlen($_POST['title']) < $minTitleChars)
    		{
    			$this->error(L('title_too_short'));
    		}
    		if (strlen($_POST['title']) > $maxTitleChars)
    		{
    			$this->error(L('title_too_long'));
    		}
    		if (strlen($_POST['details']) < $minPostChars)
    		{
    			$this->error(L('too_few_characters'));
    		}
    		if (strlen($_POST['details']) > $maxPostChars)
    		{
    			$this->error(L('too_much_characters'));
    		}
    		
    		//分类检查
			if (intval($_POST['category_id']) <= 0)
			{
				$this->error(L('category_required'));
			}

			//链接数限制检查
			if(exceed_link_limit($_POST['details']))
			{
			    $this->error(L('too_much_links'));
			}

			//验证码检查
			if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
			{
				$this->error(L('captcha_incorrect'));
			}
			
    		//内容过滤
			$tagEnable = $this->_global['tag_enable'];
    		$wordCensorEnable = $this->_global['word_censor_enable'];
	    	if ($wordCensorEnable)
	    	{
	    		$_POST['title'] = censor_text($_POST['title']);
	    		$_POST['details'] = censor_text($_POST['details']);
	    		$_POST['tags'] = !empty($_POST['tags']) && $tagEnable ? censor_text($_POST['tags']) : trim($_POST['tags']);
	    	}

	    	//积分检查
			$points = 0;
			$points += intval($_POST['reward_point']);
			$points -= get_activity_points('ask');
			if ($_POST['is_urgent'])
			{
				$points -= get_activity_points('urgent');
			}
			if ($this->_user['point_count'] < $points)
			{
				$this->error(L('no_enough_points'));
			}

	    	//是否需要审核
	    	if ($this->_userGroup['allow_direct_post'])
	    	{
	    		$message = L('question_posted');
	    	    $jumpUrl = format_question_url($qstID, $_POST['title']);
	    		$isVisible = 1;
	    	}
	    	else
	    	{
	    		$message = L('question_require_approval');
	    		$jumpUrl = $this->_global['site_url'];
	    		$isVisible = 0;
	    	}

	    	//保存数据
	    	$time = time();
	    	$expire = $time + $this->_global['question_expiration'] * 86400;
	    	$data = array(
	    		'category_id'  => intval($_POST['category_id']),
	    		'poster_id'    => intval($this->_user['user_id']),
	    		'poster_name'  => $this->_user['username'],
	    		'poster_ip'    => get_client_ip(),
	    		'title'        => trim($_POST['title']),
	    		'details'      => trim($_POST['details']),
	    		'create_time'  => $time,
	    		'expire_time'  => $expire,
	    		'markup_mode'  => $this->_global['markup_mode'],
	    		'status'       => 1,
	    		'is_reward'    => intval($_POST['reward_point']) > 0 ? 1 : 0,
	    		'is_urgent'    => intval($_POST['is_urgent']),
	    		'is_visible'   => $isVisible,
	    		'reward_point' => intval($_POST['reward_point']),
	    		'new_answer_alert' => intval($_POST['new_answer_alert']),
	        );
	    	$qstID = $this->Question->add($data);

	    	//递增用户问题数
			$this->_User->setInc('question_count', 'user_id='.$this->_user['user_id'], 1);

	    	//更新用户积分以及记录动态
	    	$this->_User->updatePointCount($this->_user['user_id'], 0-$points);
			$this->_User->logActivity($this->_user['user_id'], 'ask', 0-$points, $qstID);

	    	//更新分类问题计数
	    	$Category = D('Category');
	    	$Category->updateQuestionCount($_POST['category_id'], 'inc');

	    	/* ----------------------- 处理问题tag ----------------------------*/
	    	if ($tagEnable && !empty($_POST['tags']))
	    	{
	    	    $Tag  = D('Tag');
	    	    $QTag = D('QuestionTag');

	    	    $count = 0;
	    	    $maxCount = $this->_global['max_post_tags'];
	    		$tags = trim($_POST['tags']);
	    		$tags = filter_tags($tags);

	    		foreach ($tags as $value)
	    		{
	    			$tagName = trim($value);
	    			if (preg_match('/^([\x7f-\xff_-]|\w|\s){3,20}$/', $tagName))
	    			{
	    				$tag = $Tag->getTagByName($tagName);
						if ($tag)
						{
							$tagID = $tag['tag_id'];
							if ($tag['status'])
							{
								$Tag->setInc('question_count', 'tag_id='.$tagID, 1);
							}
						}
						else
						{
							$data = array(
								'name' => $tagName,
								'question_count' => 1,
								'status' => 1,
							);
							$tagID = $Tag->add($data);
						}

						$data = array(
							'question_id' => $qstID,
							'tag_id' => $tagID,
						);
						$QTag->add($data);

						$count++;
						if ($count > $maxCount)
						{
						    break;
						}
					}
	    		}
	    	}

	    	$jumpUrl = format_question_url($qstID, $_POST['title']);
	    	$this->assign('jumpUrl', $jumpUrl);
	    	$this->success($message);
    	}
    	else
    	{
    	    $urgentCost = 0 - get_activity_points('urgent');
	    	L('ask_tags_explain', sprintf(L('ask_tags_explain'), $this->_global['max_post_tags']));
            L('ask_urgent_cost', sprintf(L('ask_urgent_cost'), $urgentCost));
            L('user_current_points', sprintf(L('user_current_points'), intval($this->_user['point_count'])));

	    	$this->assign('title', Input::hsc(Input::getVar($_POST['title'])));
	    	$this->assign('captcha', $captcha);
	    	$this->assign('rewardOptions', L('ask_reward_options'));
	    	$this->display();
    	}
    }


    //编辑问题
    public function edit()
    {

    	$qstID = intval($_REQUEST['qid']);
    	$question = $this->Question->find($qstID);
    	if (empty($question))
    	{
 			$this->error(L('question_not_existed'));
 		}
 		
 		$question['category_path'] = get_category_path($question['category_id']);
 		
 		$captcha = require_captcha_when('post', $this->_user['user_group']);

 		/* 用户权限检查(版主任何状态下可修改，会员只能在开放状态下修改) */
    	$isModerator = is_moderator($this->_user['user_id'], $this->_user['admin_group'], $question['category_id']);
    	if ($isModerator && $this->_adminGroup['allow_edit_question'])
    	{
    	   //do nothing
    	}
    	elseif ($question['poster_id'] == $this->_user['user_id'] && $this->_userGroup['allow_edit_question'] && 1 == $question['status'])
    	{
    	    //do nothing
    	}
    	else
    	{
            $this->error(L('no_perms_action'));
    	}

    	if ($this->isPost())
    	{
    	    //内容长度检查
    		$minTitleChars = $this->_global['min_title_chars'];
    		$maxTitleChars = $this->_global['max_title_chars'];
    		$minPostChars  = $this->_global['min_post_chars'];
    		$maxPostChars  = $this->_global['max_post_chars'];
    		if (strlen($_POST['title']) < $minTitleChars)
    		{
    			$this->error(L('title_too_short'));
    		}
    		if (strlen($_POST['title']) > $maxTitleChars)
    		{
    			$this->error(L('title_too_long'));
    		}
    		if (strlen($_POST['details']) < $minPostChars)
    		{
    			$this->error(L('too_few_characters'));
    		}
    		if (strlen($_POST['details']) > $maxPostChars)
    		{
    			$this->error(L('too_much_characters'));
    		}
    		
    		//分类检查
			if (intval($_POST['category_id']) <= 0)
			{
				$this->error(L('category_required'));
			}

			//链接数限制检查
			if(exceed_link_limit($_POST['details']))
			{
			    $this->error(L('too_much_links'));
			}

	    	//验证码检查
			if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
			{
				$this->error(L('captcha_incorrect'));
			}

    		//内容过滤
    		$tagEnable  = $this->_global['tag_enable'];
			$wordCensorEnable = $this->_global['word_censor_enable'];
	    	if ($wordCensorEnable)
	    	{
	    		$_POST['title'] = censor_text($_POST['title']);
	    		$_POST['details'] = censor_text($_POST['details']);
	    		$_POST['tags'] = !empty($_POST['tags']) && $tagEnable ? censor_text($_POST['tags']) : trim($_POST['tags']);
	    	}

	    	//保存问题
	    	$data = array(
	    		'title'    => trim($_POST['title']),
	    		'details'  => trim($_POST['details']),
	    		'last_edit_time'   => time(),
	    		'last_editor_id'   => $this->_user['user_id'],
	    		'last_editor_name' => $this->_user['username'],
	    	);
	    	if ($_POST['change_category'])
	    	{
	    		$data['category_id'] = intval($_POST['category_id']);
	    	}
	    	$where = array('question_id' => $qstID);
	    	$this->Question->where($where)->save($data);

	    	//分类改变 => 更新分类问题计数
	    	$Category = D('Category');
	    	if ($_POST['change_category'] && $_POST['category_id'] != $question['category_id'])
	    	{
	    		$Category->updateQuestionCount($_POST['category_id'], 'inc', 1);
	    		$Category->updateQuestionCount($question['category_id'], 'dec', 1);
	    	}

	    	/*------------------------ 更新问题tag -------------------------*/
	    	if ($tagEnable && !empty($_POST['tags']))
	    	{
	    	    $Tag  = D('Tag');
    	    	$QTag = D('QuestionTag');

    	    	$tempIDs = array();
    	    	$tagIDs = $this->Question->getQuestionTagIDs($qstID);

	    	    $count = 0;
	    		$maxCount = $this->_global['max_post_tags'];
	    		$tags = trim($_POST['tags']);
	    		$tags = filter_tags($tags);

	    		foreach ($tags as $value)
	    		{
	    			$tagName = trim($value);
	    			if (preg_match('/^([\x7f-\xff_-]|\w|\s){3,20}$/', $tagName))
	    			{
	    				$tag = $Tag->getTagByName($tagName);
						if ($tag)
						{
							$tempIDs[] = $tag['tag_id'];
						}
						else
						{
							$data = array(
								'name' => $tagName,
								'question_count' => 1,
								'status' => 1,
							);
							$tagID = $Tag->add($data);
							$data = array(
								'question_id' => $qstID,
								'tag_id' => $tagID,
							);
							$QTag->add($data);
						}
						$count++;
						if ($count > $maxCount)
						{
						    break;
						}
					}
	    		}
	    	}

	    	//递减tag计数以及记录
    		$diff = array_diff($tagIDs, $tempIDs);
    		if ($diff)
    		{
    			$where = array('tag_id' => array('in', $diff));
    			$data  = array('question_count' => array('exp', 'question_count-1'));
    			$Tag->where($where)->save($data);
    			$where = array(
    				'question_id' => $qstID,
    				'tag_id' => array('in', $diff),
    			);
    			$QTag->where($where)->delete();
    		}

    		//递增tag计数以及记录
    		$diff = array_diff($tempIDs, $tagIDs);
    		if ($diff)
    		{
    			$where = array('tag_id' => array('in', $diff));
    			$data  = array('question_count' => array('exp', 'question_count+1'));
    			$Tag->where($where)->save($data);
    			foreach ($diff as $value)
    			{
    				$data = array(
	    				'question_id' => $qstID,
	    				'tag_id' => $value,
	    			);
    				$QTag->where($where)->replace($data);
    			}
    		}

	    	$this->assign('jumpUrl', format_question_url($qstID, $_POST['title']));
	    	$this->success(L('question_edited'));
    	}
    	else
    	{
    		$temp = array();
    		$category = get_category_path($question['category_id']);
    		$tags = $this->Question->getQuestionTags($qstID);
    		if (!empty($tags))
    		{
    			foreach ($tags as $tag)
    			{
    				$temp[] = $tag['name'];
    			}
    		}
    		$question['tags'] = implode(', ', $temp);

    		L('ask_tags_explain', sprintf(L('ask_tags_explain'), $this->_global['max_post_tags']));

    		$this->assign('question', $question);
    		$this->assign('category', $category);
            $html = $this->fetch();
    		exit($html);
    	}
    }


    // 删除问题
    public function delelte()
    {

    	$qstID = intval($_GET['qid']);
    	$question = $this->Question->find($qstID);
    	if (empty($question))
    	{
    		$this->error(L('question_not_existed'));
    	}

    	//用户权限检查
    	$isModerator = is_moderator($this->_user['user_id'], $this->_user['admin_group'], $question['category_id']);
    	$allow = ($this->_userGroup['allow_delete_question'] && $this->_user['user_id'] == $question['poster_id']) || ($isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_delete_question'));
		if (!$allow)
		{
			$this->error(L('no_perms_action'));
		}

		//更新用户积分
		$points = get_activity_points('delete_question');
		$this->_User->updatePointCount($question['poster_id'], $points);
		$this->_User->logActivity($question['poster_id'], 'delete_question', $points, $qstID);

		//删除问题
		$this->Question->deleteQuestionByID($qstID);
		$url = format_category_url($question['category_id']);
        redirect($url);
    }

}
// End Class

/* End of file QuestionAction.class.php */
/* Location: ./App/Lib/Action/Home/QuestionAction.class.php */